package com.xjtu.platform.reader.impl;

import com.xjtu.platform.common.Utils;
import com.xjtu.platform.common.dao.CommonDao;
import com.xjtu.platform.reader.BorrowService;
import com.xjtu.platform.reader.dao.BorrowDao;
import com.xjtu.platform.reader.dto.ReturnBookDto;
import com.xjtu.platform.reader.entity.BookScore;
import com.xjtu.platform.reader.entity.PenaltyUsingTime;
import com.xjtu.platform.reader.utils.BookUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;

@Service
@Transactional
public class BorrowServiceImpl implements BorrowService {

    @Resource
    private BorrowDao borrowDao;

    @Resource
    private CommonDao commonDao;

    @Override
    public boolean returnBookToHis(ReturnBookDto returnBookDto,Timestamp end_time) {
        try {
            borrowDao.updateBorrowHis(returnBookDto,end_time);

            borrowDao.returnBookNum(returnBookDto);

            borrowDao.scoreBook(returnBookDto,end_time);

            List<BookScore> scoreList = borrowDao.getBookScoreList(returnBookDto.getBook_id());

            String newScore = BookUtils.calBookAllScore(scoreList);

            borrowDao.updateBookScore(returnBookDto.getBook_id(),newScore);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean penaltyReader(String bookReaderHisId, Timestamp end_time) {
        try {
            PenaltyUsingTime penaltyUsingTime = borrowDao.getStartTime(bookReaderHisId);
            String usingTime = Utils.getTimeDifference(penaltyUsingTime.getStart_time(),end_time);
            usingTime = String.valueOf(Integer.parseInt(usingTime) - Integer.parseInt(penaltyUsingTime.getBorrow_time()));
            String money = Utils.calPenaltyMoney(usingTime,commonDao);
            if(!money.equals("")){
                borrowDao.insertUserPenalty(bookReaderHisId,money,end_time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
